<?php

/**
 * 附件删除接口
 * Some rights reserved：abc3210.com
 * Contact email:admin@abc3210.com
 */
class Attachment {

    private $db, $path, $Config, $Ftpstatus, $Ftp;

    function __construct() {
        $this->db = D("Attachment");
        $this->path = SITE_PATH . "/d/file/";
        $this->Config = F("Config");
        if ((int) $this->Config['ftpstatus']) {
            import('@.ORG.Util.Ftp');
            $this->Ftp = new Ftp();
            $this->Ftpstatus = 1;
        }
    }

    public function path($path) {
        $this->path = $path;
    }

    /**
     * 删除附件。
     * @param type $aid 附件id
     */
    public function del($aid) {
        if($this->Ftpstatus) {
            $ftpsta = $this->Ftp->connect($this->Config['ftphost'], $this->Config['ftpuser'], $this->Config['ftppassword'], $this->Config['ftpport'], $this->Config['ftppasv'], $this->Config['ftpssl'], $this->Config['ftptimeout']);
            if ($ftpsta == false) {
                $this->error = 'FTP链接失败' . $this->Config['ftphost'];
                return false;
            }
        }
        $data = $this->db->where(array("aid" => $aid))->find();
        if ($data) {
            $filepath = $data['filepath'];
            $status = $this->db->where(array("aid" => $aid))->delete();
            $status = true;
            if ($status) {
                //FTP删除
                if ($this->Ftpstatus) {
                    // 远程存放地址
                    $remote = $this->Config['ftpuppat'] . str_replace(SITE_PATH . "/", "", $this->path . $filepath);
                    $status = $this->Ftp->f_delete($remote);
                    $this->Ftp->close();
                    return $status;
                } else {
                    return unlink($this->path . $filepath);
                }
            }
        } else {
            return false;
        }
    }

    /**
     * 通过附件关系删除附件 
     */
    public function api_delete($keyid) {
        if (empty($keyid)) {
            return false;
        }
        $db = M("AttachmentIndex");
        $data = $db->where(array("keyid" => $keyid))->select();
        if ($data) {
            foreach ($data as $aid) {
                if ($this->del($aid['aid'])) {
                    
                } else {
                    return false;
                }
            }
        }
        $db->where(array("keyid" => $keyid))->delete();
        return true;
    }

}

?>
